﻿using log4net;
using Modbus.Device;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Input;
using YmSoft.WPF.Core;

namespace YmSoft.WPF.Modbus
{
    public abstract class MVMessageBase : BaseNotifyPropertyChanged
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(MVMessageBase));

        protected MVModbus mvModbus;
        public MVMessageBase(MVModbus mvModbus)
        {
            this.mvModbus = mvModbus;
        }

        byte slaveAddress = 0;
        public byte SlaveAddress
        {
            get
            {
                return this.slaveAddress;
            }

            set
            {
                if (value != this.slaveAddress)
                {
                    this.slaveAddress = value;
                    NotifyPropertyChanged("SlaveAddress");
                }
            }
        }

        ICommand sendCommand = null;
        public ICommand SendCommand
        {
            get
            {
                if (sendCommand == null)
                {
                    sendCommand = new RelayCommand(() =>
                    {
                        //PrivateSendMessage();

                        if (mvModbus.RunThread != null)
                        {
                            return;
                        }
                        mvModbus.RunThread = new Thread(new ThreadStart(PrivateSendMessage));
                        mvModbus.RunThread.Start();
                    });
                }
                return sendCommand;
            }
        }

        private void PrivateSendMessage()
        {
            if (mvModbus.RunSerialPort == null)
            {
                mvModbus.RunSerialPort = new SerialPort(mvModbus.Port);
                _logger.Info(string.Format("端口:{0}", mvModbus.Port));
                // configure serial port
                mvModbus.RunSerialPort.BaudRate = mvModbus.BaudRate;
                mvModbus.RunSerialPort.DataBits = 8;
                mvModbus.RunSerialPort.Parity = Parity.None;
                mvModbus.RunSerialPort.StopBits = StopBits.One;
                mvModbus.RunSerialPort.Open();
            }
            //while (mvModbus.RunSerialPort.IsOpen)
            if (mvModbus.RunSerialPort.IsOpen)
            {
                try
                {
                    IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(mvModbus.RunSerialPort);
                    SendMessage(master);
                    mvModbus.Message = DateTime.Now.ToString() + " OVER";
                }
                catch (ThreadAbortException ex)
                {
                }
                catch (Exception ex)
                {
                    mvModbus.Message = DateTime.Now.ToString() + " 失败:" + ex.Message;
                }
                ReadLog();

                mvModbus.RunSerialPort.Close();
                mvModbus.RunSerialPort.Dispose();
                mvModbus.RunSerialPort = null;
                mvModbus.RunThread = null;
            }
        }

        private void ReadLog()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "NModbusLog.txt";
            var path1 = AppDomain.CurrentDomain.BaseDirectory + "Copylog.txt";
            if (!File.Exists(path))
            {
                mvModbus.Log = "";
                return;
            }
            File.Copy(path, path1, true);
            var lines = File.ReadAllLines(path1, Encoding.GetEncoding("GB2312"));

            var str = string.Join("\r\n", lines.Reverse().Take(20).ToArray());
            mvModbus.Log = str;
        }

        protected virtual void SendMessage(IModbusSerialMaster master)
        {
        }
    }
}
